<template>
    <div class="add-user-role-permission-container">
        <!-- 页面标题区域 -->
        <div class="page-header">
            <div class="header-content">
                <div class="title-section">
                    <el-icon class="title-icon" size="32">
                        <UserPlus />
                    </el-icon>
                    <h1 class="page-title">添加用户角色权限</h1>
                </div>
                <p class="page-description">创建新用户并分配角色和权限</p>
            </div>
        </div>

        <!-- 表单卡片容器 -->
        <div class="form-container">
            <el-card class="form-card" shadow="hover">
                <template #header>
                    <div class="card-header">
                        <el-icon class="card-icon" size="20">
                            <Edit />
                        </el-icon>
                        <span class="card-title">用户信息</span>
                    </div>
                </template>

                <el-form ref="ruleFormRef" class="user-form" :model="ruleForm" :rules="rules" label-width="100px"
                    label-position="left">
                    <!-- 基本信息区域 -->
                    <div class="form-section">
                        <div class="section-title">
                            <el-icon class="section-icon">
                                <User />
                            </el-icon>
                            <span>基本信息</span>
                        </div>

                        <!-- 用户名输入 -->
                        <el-form-item label="用户名" prop="userName" class="form-item">
                            <el-input v-model="ruleForm.userName" placeholder="请输入用户名" clearable class="form-input">
                                <template #prefix>
                                    <el-icon class="input-icon">
                                        <User />
                                    </el-icon>
                                </template>
                            </el-input>
                        </el-form-item>

                        <!-- 密码输入 -->
                        <el-form-item label="密码" prop="password" class="form-item">
                            <el-input v-model="ruleForm.password" type="password" placeholder="请输入密码" show-password
                                clearable class="form-input">
                                <template #prefix>
                                    <el-icon class="input-icon">
                                        <Lock />
                                    </el-icon>
                                </template>
                            </el-input>
                        </el-form-item>

                        <!-- 昵称输入 -->
                        <el-form-item label="昵称" prop="nickName" class="form-item">
                            <el-input v-model="ruleForm.nickName" placeholder="请输入昵称" clearable class="form-input">
                                <template #prefix>
                                    <el-icon class="input-icon">
                                        <Avatar />
                                    </el-icon>
                                </template>
                            </el-input>
                        </el-form-item>
                    </div>

                    <!-- 角色选择区域 -->
                    <div class="form-section">
                        <div class="section-title">
                            <el-icon class="section-icon">
                                <UserFilled />
                            </el-icon>
                            <span>角色分配</span>
                        </div>

                        <el-form-item label="角色" prop="roleIds" class="form-item role-section">
                            <div class="role-container">
                                <el-checkbox-group v-model="ruleForm.roleIds" class="role-checkbox-group">
                                    <el-checkbox v-for="item in roleOptions" :key="item.roleId" :label="item.roleId"
                                        :value="item.roleId" class="role-checkbox">
                                        <div class="role-item">
                                            <el-icon class="role-icon">
                                                <UserFilled />
                                            </el-icon>
                                            <span class="role-name">{{ item.roleName }}</span>
                                        </div>
                                    </el-checkbox>
                                </el-checkbox-group>
                            </div>
                        </el-form-item>
                    </div>

                    <!-- 权限选择区域 -->
                    <div class="form-section">
                        <div class="section-title">
                            <el-icon class="section-icon">
                                <Key />
                            </el-icon>
                            <span>权限分配</span>
                        </div>

                        <el-form-item label="权限" prop="permissionIds" class="form-item permission-section">
                            <div class="permission-container">
                                <el-checkbox-group v-model="ruleForm.permissionIds" class="permission-checkbox-group">
                                    <el-checkbox v-for="item in permissionOptions" :key="item.permissonId"
                                        :label="item.permissonId" :value="item.permissonId" class="permission-checkbox">
                                        <div class="permission-item">
                                            <el-icon class="permission-icon">
                                                <Key />
                                            </el-icon>
                                            <span class="permission-name">{{ item.permissonName }}</span>
                                        </div>
                                    </el-checkbox>
                                </el-checkbox-group>
                            </div>
                        </el-form-item>
                    </div>

                    <!-- 按钮区域 -->
                    <el-form-item class="button-section">
                        <div class="button-group">
                            <el-button type="primary" size="large" :loading="isSubmitting"
                                @click="submitForm(ruleFormRef)" class="submit-btn">
                                <el-icon class="btn-icon">
                                    <Check />
                                </el-icon>
                                添加用户
                            </el-button>
                            <el-button size="large" @click="resetForm(ruleFormRef)" class="reset-btn">
                                <el-icon class="btn-icon">
                                    <Refresh />
                                </el-icon>
                                重置表单
                            </el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import { read, write } from '@/Until/axiosHepler'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import {

    Edit,
    User,
    Lock,
    Avatar,
    UserFilled,
    Key,
    Check,
    Refresh
} from '@element-plus/icons-vue'

const router = useRouter()

interface RuleForm {
    userName: string
    password: string
    nickName: string
    roleIds: any[]
    permissionIds: any[]
}

const ruleFormRef = ref<FormInstance>()
const isSubmitting = ref(false)
const ruleForm = reactive<RuleForm>({
    userName: "",
    password: "",
    nickName: "",
    roleIds: [],
    permissionIds: []
})

const roleOptions = ref<any[]>([])
const permissionOptions = ref<any[]>([])

const roleList = () => {
    read.get("api/User/RoleList").then((res) => {
        roleOptions.value = res.data.data;
    })
}

const permissionList = () => {
    read.get("api/User/PermissonList").then((res) => {
        permissionOptions.value = res.data.data;
    })
}

onMounted(() => {
    roleList();
    permissionList();
})

const rules = reactive<FormRules<RuleForm>>({
    userName: [
        { required: true, message: '请输入用户名', trigger: 'blur' },

    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
    ],
    nickName: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
    ],



})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    // 基本验证
    if (!ruleForm.userName.trim()) {
        ElMessage.warning('请输入用户名')
        return
    }
    if (!ruleForm.nickName.trim()) {
        ElMessage.warning('请输入昵称')
        return
    }
    if (!ruleForm.password.trim()) {
        ElMessage.warning('请输入密码')
        return
    }
    if (!ruleForm.roleIds || ruleForm.roleIds.length === 0) {
        ElMessage.warning('请至少选择一个角色')
        return
    }
    if (!ruleForm.permissionIds || ruleForm.permissionIds.length === 0) {
        ElMessage.warning('请至少选择一个权限')
        return
    }

    try {
        await formEl.validate(async (valid, fields) => {
            if (valid) {
                isSubmitting.value = true
                try {
                    const res = await write.post("api/Manger/AddUser", ruleForm)
                    if (res.data.code == 200) {
                        ElMessage.success("添加用户角色权限成功")
                        router.push("/MainView/RoleUserView")
                    } else {
                        ElMessage.error(res.data.message || "添加用户角色权限失败")
                    }
                } catch (error) {
                    console.error('提交失败:', error)
                    ElMessage.error("网络错误，请稍后重试")
                } finally {
                    isSubmitting.value = false
                }
            } else {
                ElMessage.warning("请检查表单填写是否完整")
            }
        })
    } catch (error) {
        console.error('表单验证失败:', error)
    }
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))
</script>